// ------------------------------------------------------------------------------------------
// Licensed by Interprise Solutions.
// http://www.InterpriseSolutions.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
using InterpriseSuiteEcommerceControls.Validators;
using InterpriseSuiteEcommerceControls.Validators.Special;
using InterpriseSuiteEcommerceCommon;
using InterpriseSuiteEcommerceCommon.DTO;

namespace InterpriseSuiteEcommerceControls
{
    public class PaymentTermControl : BaseFormFieldControl
    {

        #region Variable Declaration

        public const string PAYMENT_METHOD_CHECK = "Check/Cheque";
        public const string PAYMENT_METHOD_CREDITCARD = "Credit Card";
        public const string PAYMENT_METHOD_CASH = "Cash/Other";
        public const string PAYMENT_METHOD_PAYPALX = "PayPal";

        private const string PAYMENT_TERM_TEMP_ATTRIBUTE = "pr";
        private const string PAYMENT_METHOD_TEMP_ATTRIBUTE = "pm";
        private const string TEMP_PAYMENT_TERM_ID = "TemporaryPaymentTermID";
        private const string PAYMENT_TERM_REQUIRED_ERROR_MESSAGE = "PaymentTermRequiredErrorMessage";
        private const string NAME_ON_CARD_REQUIRED_ERROR_MESSAGE = "NameOnCardRequiredErrorMessage";
        private const string CARD_NUMBER_REQUIRED_ERROR_MESSAGE = "CardNumberRequiredErrorMessage";
        private const string CVV_REQUIRED_ERROR_MESSAGE = "CVVRequiredErrorMessage";
        private const string CARD_TYPE_INVALID_ERROR_MESSAGE = "CardTypeInvalidErrorMessage";
        private const string START_MONTH_INVALID_ERROR_MESSAGE = "StartMonthInvalidErrorMessage";
        private const string START_YEAR_INVALID_ERROR_MESSAGE = "StartYearInvalidErrorMessage";

        private const string EXPIRATION_MONTH_INVALID_ERROR_MESSAGE = "ExpirationMonthInvalidErrorMessage";
        private const string EXPIRATION_YEAR_INVALID_ERROR_MESSAGE = "ExpirationYearInvalidErrorMessage";
        private const string UNKNOWN_CARD_TYPE_ERROR_MESSAGE = "UnknownCardTypeErrorMessage";
        private const string NO_CARD_NUMBER_PROVIDED_ERROR_MESSAGE = "NoCardNumberProvidedErrorMessage";
        private const string CARD_NUMBER_INVALID_FORMAT_ERROR_MESSAGE = "CardNumberInvalidFormatErrorMessage";
        private const string CARD_NUMBER_INVALID_ERROR_MESSAGE = "CardNumberInvalidErrorMessage";
        private const string STORED_CARD_NUMBER_INVALID_ERROR_MESSAGE = "StoredCardNumberInvalidErrorMessage";
        private const string CARD_NUMBER_INAPPROPRIATE_NUMBER_OF_DIGITS_ERROR_MESSAGE = "CardNumberInAppropriateNumberOfDigitsErrorMessage";
        private const string NO_PAYMENT_REQUIRED = "NoPaymentRequired";
        private const string SHOW_CARD_START_DATE = "ShowCardStartDate";

        private const string TERMS_AND_CONDITIONS_HTML = "TermsAndConditionsHTML";
        private const string REQUIRE_TERMS_AND_CONDITIONS = "RequireTermsAndConditions";
        private const string TERMS_AND_CONDITIONS_PROMPT = "TermsAndConditionsPrompt";

        private Label _lblNameOnCardCaption = null;
        private TextBox _txtNameOnCard = null;
        private Label _lblCardNumberCaption = null;
        private TextBox _txtCardNumber = null;
        private Label _lblCVVCaption = null;
        private TextBox _txtCVV = null;
        private Label _lblCardTypeCaption = null;
        private DropDownList _cboCardType = null;
        private Label _lblExpirationDateCaption = null;
        private DropDownList _cboExpirationMonth = null;
        private DropDownList _cboExpirationYear = null;
        private Label _lblCardStartDateCaption = null;
        private DropDownList _cboStartMonth = null;
        private DropDownList _cboStartYear = null;
        private Label _lblCardIssueNumberCaption = null;
        private TextBox _txtCardIssueNumber = null;
        private Label _lblCardIssueNumberInfoCaption = null;
        private Label _lblPONumber = null;
        private TextBox _txtPONumber = null;
        private Label _lblRedirectCaption = null;

        private CheckBox _chkTermsChecked = null;
        
        private List<HtmlInputRadioButton> _options = new List<HtmlInputRadioButton>();

        private Table _template = new Table();
        private Table _tblCreditCard = new Table();
        private Table _tblPONumber = new Table();
        private Table _tblRedirect = new Table();
        private TableRow _cardFormRow= null;
        private TableRow _poNumberRow = null;
        private TableRow _redirectRow = null;
        private HtmlInputHidden _hdfPaymentTerm = null;
        private HtmlInputHidden _hdfPaymentMethod = null;

        private HyperLink _lnkWhatIsCvv = null;

        private Label _lblNoPaymentRequired = null;


        private IEnumerable<PaymentTermDTO> _termOptions = null;
        #endregion

        #region Constructor

        public PaymentTermControl() : base()
        {
            _hdfPaymentTerm = new HtmlInputHidden();
            _hdfPaymentMethod = new HtmlInputHidden();
            _lblNameOnCardCaption = new Label();
            _txtNameOnCard = new TextBox();
            _lblCardNumberCaption = new Label();
            _txtCardNumber = new TextBox();

            //disable the readonly textbox
            _txtCardNumber.ReadOnly = false;

            _lblCVVCaption = new Label();
            _txtCVV = new TextBox();
            _lblCardTypeCaption = new Label();
            _cboCardType = new DropDownList();
            _lblExpirationDateCaption = new Label();
            _cboExpirationMonth = new DropDownList();
            _cboExpirationYear = new DropDownList();
            _lblCardStartDateCaption = new Label();
            _cboStartMonth = new DropDownList();
            _cboStartYear = new DropDownList();
            _lblCardIssueNumberCaption = new Label();
            _txtCardIssueNumber = new TextBox();
            _lblCardIssueNumberInfoCaption = new Label();
            
            _lnkWhatIsCvv = new HyperLink();
            _lnkWhatIsCvv.NavigateUrl = "javascript:void(0);";
            
            _lblNoPaymentRequired = new Label();

            _lblPONumber = new Label();
            _txtPONumber = new TextBox();

            _lblRedirectCaption = new Label();

            _template = new Table();
            _tblCreditCard = new Table();
            _tblPONumber = new Table();
            _tblRedirect = new Table();

            _cardFormRow = new TableRow();
            _poNumberRow = new TableRow();
            _redirectRow = new TableRow();

            _chkTermsChecked = new CheckBox();
            
            AssignClientReferenceIDs();

            DisableAutoComplete();
        }

        #endregion

        private void AssignClientReferenceIDs()
        {
            _hdfPaymentTerm.ID = "PaymentTerm";
            _hdfPaymentMethod.ID = "PaymentMethod";
            _txtNameOnCard.ID = "NameOnCard";
            _txtCardNumber.ID = "CardNumber";

            _txtCardNumber.ReadOnly = false;

            _txtCVV.ID = "CVV";
            _cboCardType.ID = "CardType";
            _cboExpirationMonth.ID = "ExpirationMonth";
            _cboExpirationYear.ID = "ExpirationYear";
            _lnkWhatIsCvv.ID = "WhatIsCVV";
            _cboStartMonth.ID = "StartMonth";
            _cboStartYear.ID = "StartYear";
            _txtCardIssueNumber.ID = "CardIssueNumber";

            _cardFormRow.ID = "CardFormRow";
            _poNumberRow.ID = "PONumberRow";
            _redirectRow.ID = "ExternalRow";

            _chkTermsChecked.ID = "TermsAndConditionsChecked";
        }

        private void DisableAutoComplete()
        {
            _txtCardNumber.AutoCompleteType = AutoCompleteType.Disabled;
            _txtCVV.AutoCompleteType = AutoCompleteType.Disabled;

            _txtCardNumber.Attributes["autocomplete"] = "off";
            _txtCVV.Attributes["autocomplete"] = "off";
        }

        #region Properties

        [Browsable(true), Category(APPEARANCE_CATEGORY)]
        public string NoPaymentRequiredCaption
        {
            get { return _lblNoPaymentRequired.Text; }
            set { _lblNoPaymentRequired.Text = value; }
        }

        [Browsable(true), Category(APPEARANCE_CATEGORY)]
        public string NameOnCardCaption
        {
            get { return _lblNameOnCardCaption.Text; }
            set { _lblNameOnCardCaption.Text = value; }
        }

        [Browsable(true), Category(APPEARANCE_CATEGORY)]
        public string CardNumberCaption
        {
            get { return _lblCardNumberCaption.Text; }
            set { _lblCardNumberCaption.Text = value; }
        }

        [Browsable(true), Category(APPEARANCE_CATEGORY)]
        public string CVVCaption
        {
            get { return _lblCVVCaption.Text; }
            set { _lblCVVCaption.Text = value; }
        }

        [Browsable(true), Category(APPEARANCE_CATEGORY)]
        public string CardTypeCaption
        {
            get { return _lblCardTypeCaption.Text; }
            set { _lblCardTypeCaption.Text = value; }
        }

        [Browsable(true), Category(APPEARANCE_CATEGORY)]
        public string ExpirationDateCaption
        {
            get { return _lblExpirationDateCaption.Text; }
            set { _lblExpirationDateCaption.Text = value; }
        }
        
        [Browsable(true), Category(APPEARANCE_CATEGORY)]
        public string WhatIsCVVCaption
        {
            get { return _lnkWhatIsCvv.Text; }
            set { _lnkWhatIsCvv.Text = value; }
        }

        [Browsable(true), Category(APPEARANCE_CATEGORY)]
        public string CardStartDateCaption
        {
            get { return _lblCardStartDateCaption.Text; }
            set { _lblCardStartDateCaption.Text = value; }
        }

        [Browsable(true), Category(APPEARANCE_CATEGORY)]
        public string CardIssueNumberCaption
        {
            get { return _lblCardIssueNumberCaption.Text; }
            set { _lblCardIssueNumberCaption.Text = value; }
        }

        [Browsable(true), Category(APPEARANCE_CATEGORY)]
        public string CardIssueNumberInfoCaption
        {
            get { return _lblCardIssueNumberInfoCaption.Text; }
            set { _lblCardIssueNumberInfoCaption.Text = value; }
        }

        [Browsable(false)]
        public string NameOnCard
        {
            get { return _txtNameOnCard.Text; }
            set { _txtNameOnCard.Text = value; }
        }

        [Browsable(false)]
        public string CardNumber
        {
            get { return _txtCardNumber.Text; }
            set { _txtCardNumber.Text = value; }
        }

        [Browsable(false)]
        public string CVV
        {
            get { return _txtCVV.Text; }
            set { _txtCVV.Text = value; }
        }

        public TextBox CardNumberControl
        {
            get { return _txtCardNumber; }
        }

        public TextBox CCVCControl
        {
            get { return _txtCVV; }
        }

        [Browsable(false)]
        public string CardType
        {
            get
            {
                if (null != _cboCardType.SelectedItem)
                {
                    return _cboCardType.SelectedValue;
                }
                else
                {
                    return string.Empty;
                }
            }
            set
            {
                try
                {
                    _cboCardType.SelectedValue = value;
                }
                catch
                {
                    _cboCardType.SelectedValue = null;
                }
            }
        }

        public string CardStartMonth
        {
            get
            {
                if (null != _cboStartMonth.SelectedItem)
                {
                    return _cboStartMonth.SelectedValue;
                }
                else
                {
                    return string.Empty;
                }
            }
            set
            {
                try
                {
                    _cboStartMonth.SelectedValue = value;
                }
                catch
                {
                    _cboStartMonth.SelectedValue = null;
                }
            }
        }

        [Browsable(false)]
        public string CardStartYear
        {
            get
            {
                if (null != _cboStartYear.SelectedItem)
                {
                    return _cboStartYear.SelectedValue;
                }
                else
                {
                    return string.Empty;
                }
            }
            set
            {
                try
                {
                    _cboStartYear.SelectedValue = value;
                }
                catch
                {
                    _cboStartYear.SelectedValue = null;
                }
            }
        }

        [Browsable(false)]
        public string CardIssueNumber
        {
            get { return _txtCardIssueNumber.Text; }
            set { _txtCardIssueNumber.Text = value; }
        }

        [Browsable(false)]
        public string CardExpiryMonth
        {
            get
            {
                if (null != _cboExpirationMonth.SelectedItem)
                {
                    return _cboExpirationMonth.SelectedValue;
                }
                else
                {
                    return string.Empty;
                }
            }
            set
            {
                try
                {
                    _cboExpirationMonth.SelectedValue = value;
                }
                catch
                {
                    _cboExpirationMonth.SelectedValue = null;
                }
            }
        }

        [Browsable(false)]
        public string CardExpiryYear
        {
            get
            {
                if (null != _cboExpirationYear.SelectedItem)
                {
                    return _cboExpirationYear.SelectedValue;
                }
                else
                {
                    return string.Empty;
                }
            }
            set
            {
                try
                {
                    _cboExpirationYear.SelectedValue = value;
                }
                catch
                {
                    _cboExpirationYear.SelectedValue = null;
                }
            }
        }

        [Browsable(true)]
        public string PONumberCaption
        {
            get { return _lblPONumber.Text; }
            set { _lblPONumber.Text = value; }
        }

        [Browsable(true)]
        public string PONumber
        {
            get { return _txtPONumber.Text; }
            set { _txtPONumber.Text = value; }
        }

        [Browsable(true)]
        public string ExternalCaption
        {
            get { return _lblRedirectCaption.Text; }
            set { _lblRedirectCaption.Text = value; }
        }

        [Browsable(false)]
        public IEnumerable CardTypeDataSource
        {
            get { return _cboCardType.DataSource as IEnumerable; }
            set 
            {
                _cboCardType.DataSource = value;
                _cboCardType.DataBind();
            }
        }

        [Browsable(false)]
        public System.Data.DataView CardTypeViewDataSource
        {
            get { return _cboCardType.DataSource as System.Data.DataView; }
            set
            {
                _cboCardType.DataSource = value;
                _cboCardType.DataTextField = "CreditCardTypeDescription";
                _cboCardType.DataValueField = "CreditCardType";
                _cboCardType.DataBind();
            }
        }

        [Browsable(false)]
        public IEnumerable StartMonthDataSource
        {
            get { return _cboStartMonth.DataSource as IEnumerable; }
            set
            {
                _cboStartMonth.DataSource = value;
                _cboStartMonth.DataBind();
            }
        }

        [Browsable(false)]
        public IEnumerable StartYearDataSource
        {
            get { return  _cboStartYear.DataSource as IEnumerable; }
            set
            {
                _cboStartYear.DataSource = value;
                _cboStartYear.DataBind();
            }
        }

        [Browsable(false)]
        public IEnumerable ExpiryMonthDataSource
        {
            get { return _cboExpirationMonth.DataSource as IEnumerable; }
            set
            {
                _cboExpirationMonth.DataSource = value;
                _cboExpirationMonth.DataBind();
            }
        }

        [Browsable(false)]
        public IEnumerable ExpiryYearDataSource
        {
            get { return _cboExpirationYear.DataSource as IEnumerable; }
            set
            {
                _cboExpirationYear.DataSource = value;
                _cboExpirationYear.DataBind();
            }
        }

        [Browsable(true), Category(VALIDATORS_CATEGORY)]
        public string PaymentTermRequiredErrorMessage
        {
            get
            {
                object savedValue = ViewState[PAYMENT_TERM_REQUIRED_ERROR_MESSAGE];
                if (null == savedValue) { return string.Empty; }

                return savedValue.ToString();
            }
            set
            {
                ViewState[PAYMENT_TERM_REQUIRED_ERROR_MESSAGE] = value;
            }
        }

        [Browsable(true), Category(VALIDATORS_CATEGORY)]
        public string NameOnCardRequiredErrorMessage
        {
            get
            {
                object savedValue = ViewState[NAME_ON_CARD_REQUIRED_ERROR_MESSAGE];
                if (null == savedValue) { return string.Empty; }

                return savedValue.ToString();
            }
            set
            {
                ViewState[NAME_ON_CARD_REQUIRED_ERROR_MESSAGE] = value;
            }
        }

        [Browsable(true), Category(VALIDATORS_CATEGORY)]
        public string CardNumberRequiredErrorMessage
        {
            get
            {
                object savedValue = ViewState[CARD_NUMBER_REQUIRED_ERROR_MESSAGE];
                if (null == savedValue) { return string.Empty; }

                return savedValue.ToString();
            }
            set
            {
                ViewState[CARD_NUMBER_REQUIRED_ERROR_MESSAGE] = value;
            }
        }

        [Browsable(true), Category(VALIDATORS_CATEGORY)]
        public string CVVRequiredErrorMessage
        {
            get
            {
                object savedValue = ViewState[CVV_REQUIRED_ERROR_MESSAGE];
                if (null == savedValue) { return string.Empty; }

                return savedValue.ToString();
            }
            set
            {
                ViewState[CVV_REQUIRED_ERROR_MESSAGE] = value;
            }
        }

        [Browsable(true), Category(VALIDATORS_CATEGORY)]
        public string CardTypeInvalidErrorMessage
        {
            get
            {
                object savedValue = ViewState[CARD_TYPE_INVALID_ERROR_MESSAGE];
                if (null == savedValue) { return string.Empty; }

                return savedValue.ToString();
            }
            set
            {
                ViewState[CARD_TYPE_INVALID_ERROR_MESSAGE] = value;
            }
        }

        [Browsable(true), Category(VALIDATORS_CATEGORY)]
        public string StartMonthInvalidErrorMessage
        {
            get
            {
                object savedValue = ViewState[START_MONTH_INVALID_ERROR_MESSAGE];
                if (null == savedValue) { return string.Empty; }

                return savedValue.ToString();
            }
            set
            {
                ViewState[START_MONTH_INVALID_ERROR_MESSAGE] = value;
            }
        }

        [Browsable(true), Category(VALIDATORS_CATEGORY)]
        public string StartYearInvalidErrorMessage
        {
            get
            {
                object savedValue = ViewState[START_YEAR_INVALID_ERROR_MESSAGE];
                if (null == savedValue) { return string.Empty; }

                return savedValue.ToString();
            }
            set
            {
                ViewState[START_YEAR_INVALID_ERROR_MESSAGE] = value;
            }
        }

        [Browsable(true), Category(VALIDATORS_CATEGORY)]
        public string ExpirationMonthInvalidErrorMessage
        {
            get
            {
                object savedValue = ViewState[EXPIRATION_MONTH_INVALID_ERROR_MESSAGE];
                if (null == savedValue) { return string.Empty; }

                return savedValue.ToString();
            }
            set
            {
                ViewState[EXPIRATION_MONTH_INVALID_ERROR_MESSAGE] = value;
            }
        }

        [Browsable(true), Category(VALIDATORS_CATEGORY)]
        public string ExpirationYearInvalidErrorMessage
        {
            get
            {
                object savedValue = ViewState[EXPIRATION_YEAR_INVALID_ERROR_MESSAGE];
                if (null == savedValue) { return string.Empty; }

                return savedValue.ToString();
            }
            set
            {
                ViewState[EXPIRATION_YEAR_INVALID_ERROR_MESSAGE] = value;
            }
        }

        [Browsable(true), Category(VALIDATORS_CATEGORY)]
        public string UnknownCardTypeErrorMessage
        {
            get
            {
                object savedValue = ViewState[UNKNOWN_CARD_TYPE_ERROR_MESSAGE];
                if (null == savedValue) { return string.Empty; }

                return savedValue.ToString();
            }
            set
            {
                ViewState[UNKNOWN_CARD_TYPE_ERROR_MESSAGE] = value;
            }
        }

        [Browsable(true), Category(VALIDATORS_CATEGORY)]
        public string NoCardNumberProvidedErrorMessage
        {
            get
            {
                object savedValue = ViewState[NO_CARD_NUMBER_PROVIDED_ERROR_MESSAGE];
                if (null == savedValue) { return string.Empty; }

                return savedValue.ToString();
            }
            set
            {
                ViewState[NO_CARD_NUMBER_PROVIDED_ERROR_MESSAGE] = value;
            }
        }

        [Browsable(true), Category(VALIDATORS_CATEGORY)]
        public string CardNumberInvalidFormatErrorMessage
        {
            get
            {
                object savedValue = ViewState[CARD_NUMBER_INVALID_FORMAT_ERROR_MESSAGE];
                if (null == savedValue) { return string.Empty; }

                return savedValue.ToString();
            }
            set
            {
                ViewState[CARD_NUMBER_INVALID_FORMAT_ERROR_MESSAGE] = value;
            }
        }

        [Browsable(true), Category(VALIDATORS_CATEGORY)]
        public string CardNumberInvalidErrorMessage
        {
            get
            {
                object savedValue = ViewState[CARD_NUMBER_INVALID_ERROR_MESSAGE];
                if (null == savedValue) { return string.Empty; }

                return savedValue.ToString();
            }
            set
            {
                ViewState[CARD_NUMBER_INVALID_ERROR_MESSAGE] = value;
            }
        }

        [Browsable(true), Category(VALIDATORS_CATEGORY)]
        public string StoredCardNumberInvalidErrorMessage
        {
            get
            {
                object savedValue = ViewState[STORED_CARD_NUMBER_INVALID_ERROR_MESSAGE];
                if (null == savedValue) { return string.Empty; }

                return savedValue.ToString();
            }
            set
            {
                ViewState[STORED_CARD_NUMBER_INVALID_ERROR_MESSAGE] = value;
            }
        }

        [Browsable(true), Category(VALIDATORS_CATEGORY)]
        public string CardNumberInAppropriateNumberOfDigitsErrorMessage
        {
            get
            {
                object savedValue = ViewState[CARD_NUMBER_INAPPROPRIATE_NUMBER_OF_DIGITS_ERROR_MESSAGE];
                if (null == savedValue) { return string.Empty; }

                return savedValue.ToString();
            }
            set
            {
                ViewState[CARD_NUMBER_INAPPROPRIATE_NUMBER_OF_DIGITS_ERROR_MESSAGE] = value;
            }
        }

        public string TermsAndConditionsHTML
        {
            get
            {
                object savedValue = ViewState[TERMS_AND_CONDITIONS_HTML];
                if (null == savedValue) { return string.Empty; }

                return savedValue.ToString();
            }
            set
            {
                ViewState[TERMS_AND_CONDITIONS_HTML] = value;
            }
        }

        public string RequireTermsAndConditionsPrompt
        {
            get
            {
                object savedValue = ViewState[TERMS_AND_CONDITIONS_PROMPT];
                if (null == savedValue) { return string.Empty; }

                return savedValue.ToString();
            }
            set
            {
                ViewState[TERMS_AND_CONDITIONS_PROMPT] = value;
            }
        }

        public bool RequireTermsAndConditions
        {
            get
            {
                object savedValue = ViewState[REQUIRE_TERMS_AND_CONDITIONS];
                return null != savedValue && savedValue is bool && (bool)savedValue;
            }
            set
            {
                ViewState[REQUIRE_TERMS_AND_CONDITIONS] = value;
            }
        }

        [Browsable(true), Category(APPEARANCE_CATEGORY)]
        public bool ShowCardStarDate
        {
            get
            {
                object savedValue = ViewState[SHOW_CARD_START_DATE];
                return null != savedValue && savedValue is bool && (bool)savedValue;
            }
            set
            {
                ViewState[SHOW_CARD_START_DATE] = value;
            }
        }
        

        [Browsable(true), Category(APPEARANCE_CATEGORY)]
        public bool NoPaymentRequired
        {
            get
            {
                object savedValue = ViewState[NO_PAYMENT_REQUIRED];
                return null != savedValue && savedValue is bool && (bool)savedValue;
            }
            set
            {
                ViewState[NO_PAYMENT_REQUIRED] = value;
            }
        }

        public IEnumerable<PaymentTermDTO> PaymentTermOptions
        {
            get { return _termOptions; }
            set 
            { 
                _termOptions = value;
            }
        }

        public string PaymentTermCode
        {
            get 
            {
                return _hdfPaymentTerm.Value;
            }
        }

        public string PaymentMethod
        {
            get { return _hdfPaymentMethod.Value; }
            set { _hdfPaymentMethod.Value = value; }
        }

        public bool IsTokenization
        {
            get
            {

                if (ViewState["IsTokenization"] != null)
                {
                    return bool.Parse(ViewState["IsTokenization"].ToString());
                }
                return false;
            }
            set
            {
                ViewState["IsTokenization"] = value;
            }
        }


        public bool IsInOnePageCheckOut
        {
            get
            {
                if (ViewState["IsInOnePageCheckOut"] != null)
                {
                    return bool.Parse(ViewState["IsInOnePageCheckOut"].ToString());
                }
                return false;
            }
            set
            {
                ViewState["IsInOnePageCheckOut"] = value;
            }
        }

        #endregion

        #region Methods
        
        protected override void  CreateChildControls()
        {
            if (!Visible) return;

            if (this.NoPaymentRequired)
            {
                Panel pnlNoPayment = new Panel();
                pnlNoPayment.HorizontalAlign = HorizontalAlign.Center;
                pnlNoPayment.Controls.Add(_lblNoPaymentRequired);
                pnlNoPayment.Width = Unit.Percentage(100);
                pnlNoPayment.Controls.Add(new LiteralControl("<br />"));
                pnlNoPayment.Height = Unit.Pixel(20);

                Controls.Add(pnlNoPayment);
            }
            else
            {
                _cardFormRow.Style["display"] = "none";
                _poNumberRow.Style["display"] = "none";
                _redirectRow.Style["display"] = "none";

                Controls.Add(_hdfPaymentTerm);
                Controls.Add(_hdfPaymentMethod);

                _template.Width = Unit.Percentage(100);
                FormFieldBuilder templateBuilder = new FormFieldBuilder(_template);
                int ctr = 1;
                Boolean insertPaypal = true;
                String imageURL = string.Empty;
                LiteralControl display;

                foreach (PaymentTermDTO term in _termOptions)
                {
                    templateBuilder.NewRow();
                    HtmlInputRadioButton option = new HtmlInputRadioButton();
                    option.ID = this.ClientID + "_" + ctr.ToString();
                    option.Attributes.Add(PAYMENT_TERM_TEMP_ATTRIBUTE, term.PaymentTermCode);
                    option.Attributes.Add(PAYMENT_METHOD_TEMP_ATTRIBUTE, term.PaymentMethod);

                    if (term.PaymentMethod == PAYMENT_METHOD_CREDITCARD)
                    {
                        imageURL = "<img align=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/skin_" + Customer.Current.SkinID.ToString() + "/images/visa.gif") + "\" border=\"0\" width=\"30\" height=\"20\"/> &#160;" +
                           "<img align=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/skin_" + Customer.Current.SkinID.ToString() + "/images/discover.gif") + "\" border=\"0\" width=\"30\" height=\"20\"/> &#160;" +
                           "<img align=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/skin_" + Customer.Current.SkinID.ToString() + "/images/amex.gif") + "\" border=\"0\" width=\"30\" height=\"20\"/> &#160;" +
                           "<img align=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/skin_" + Customer.Current.SkinID.ToString() + "/images/mastercard.gif") + "\" border=\"0\" width=\"30\" height=\"20\"/> &#160;";
                    }

                    display = new LiteralControl(string.Format("{0} - {1}", imageURL + Security.HtmlEncode(term.PaymentTermCode), Security.HtmlEncode(term.Description)));
                    templateBuilder.AddCell(FormFieldBuilder.ALIGN_LEFT, Unit.Percentage(100), option, display);
                    templateBuilder.CommitRow();
                    _options.Add(option);
                    imageURL = "";
                    ctr++;

                    if (term.IsSelected)
                    {
                        option.Checked = true;

                        // now let's set the default visibility of the form
                        if (term.PaymentTermCode.ToUpper().Equals("PURCHASE ORDER"))
                        {
                            _poNumberRow.Style["display"] = "";
                        }
                        else if (term.PaymentTermCode.ToUpper().Equals("REQUEST QUOTE"))
                        {
                        }
                        else if (term.PaymentTermCode.ToUpper().Equals("PAYPAL"))
                        {
                            _redirectRow.Style["display"] = "";
                            this.PaymentMethod = PAYMENT_METHOD_PAYPALX;
                        }
                        else if (term.PaymentMethod == PAYMENT_METHOD_CREDITCARD)
                        {
                            _cardFormRow.Style["display"] = "";
                            this.PaymentMethod = PAYMENT_METHOD_CREDITCARD;
                        }
                    }

                    if (term.PaymentMethod == PAYMENT_METHOD_CREDITCARD && insertPaypal && AppLogic.AppConfigBool("PayPalCheckout.ShowOnCartPage"))
                    {
                        //Insert Paypal Express selection.
                        templateBuilder.NewRow();
                        option = new HtmlInputRadioButton();
                        option.ID = this.ClientID + "_" + ctr.ToString();
                        option.Attributes.Add(PAYMENT_TERM_TEMP_ATTRIBUTE, PAYMENT_METHOD_PAYPALX);
                        option.Attributes.Add(PAYMENT_METHOD_TEMP_ATTRIBUTE, PAYMENT_METHOD_PAYPALX);

                        StringBuilder tmpS = new StringBuilder(10000);

                        string payPalimageURL = "";
                        payPalimageURL = tmpS.Append("<a href=\"#\" onclick=\"javascript:window.open('https://www.paypal.com/us/cgi-bin/webscr?cmd=xpt/Marketing/popup/OLCWhatIsPayPal-outside','olcwhatispaypal','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes,resizable=yes,width=400,height=350');\"><img align=\"absmiddle\" src=\"https://www.paypal.com/en_US/i/logo/PayPal_mark_37x23.gif\" border=\"0\" alt=\"Acceptance Mark\"></a> &#160;").ToString();

                        display =new LiteralControl(
                                string.Format(
                                "{0} - {1}", payPalimageURL +
                                Security.HtmlEncode(AppLogic.GetString("pm.paypal.display", Customer.Current.SkinID, Customer.Current.LocaleSetting, true)),
                                Security.HtmlEncode(AppLogic.GetString("pm.paypaldescription.display", Customer.Current.SkinID, Customer.Current.LocaleSetting, true))
                            )
                        );

                        templateBuilder.AddCell(FormFieldBuilder.ALIGN_LEFT, Unit.Percentage(100), option, display);
                        templateBuilder.CommitRow();
                        _options.Add(option);
                        insertPaypal = false;
                        ctr++;
                    }
                }

                _tblCreditCard.Width = Unit.Percentage(100);
                _tblCreditCard.CssClass = "CreditCardPaymentMethodPanel";
                FormFieldBuilder cardFormBuilder = new FormFieldBuilder(_tblCreditCard);

                cardFormBuilder.NewRow();
                cardFormBuilder.AddCell(FormFieldBuilder.ALIGN_RIGHT, this.CaptionWidth, _lblNameOnCardCaption);
                cardFormBuilder.AddCell(FormFieldBuilder.ALIGN_LEFT, this.InputWidth, _txtNameOnCard);
                _txtNameOnCard.MaxLength = 100;
                _txtNameOnCard.Columns = 50;
                cardFormBuilder.CommitRow();

                cardFormBuilder.NewRow();
                cardFormBuilder.AddCell(FormFieldBuilder.ALIGN_RIGHT, this.CaptionWidth, _lblCardNumberCaption);
                cardFormBuilder.AddCell(FormFieldBuilder.ALIGN_LEFT, this.InputWidth, _txtCardNumber);
                _txtCardNumber.MaxLength = 100;
                _txtCardNumber.Columns = 30;
                cardFormBuilder.CommitRow();

                cardFormBuilder.NewRow();
                cardFormBuilder.AddCell(FormFieldBuilder.ALIGN_RIGHT, this.CaptionWidth, _lblCVVCaption);
                cardFormBuilder.AddCell(FormFieldBuilder.ALIGN_LEFT, this.InputWidth, _txtCVV, new LiteralControl(" ("), _lnkWhatIsCvv, new LiteralControl(")"));
                _txtCVV.MaxLength = 10;
                _txtCVV.Columns = 5;
                cardFormBuilder.CommitRow();

                cardFormBuilder.NewRow();
                cardFormBuilder.AddCell(FormFieldBuilder.ALIGN_RIGHT, this.CaptionWidth, _lblCardTypeCaption);
                cardFormBuilder.AddCell(FormFieldBuilder.ALIGN_LEFT, this.InputWidth, _cboCardType);
                cardFormBuilder.CommitRow();

                if (this.ShowCardStarDate)
                {
                    cardFormBuilder.NewRow();
                    cardFormBuilder.AddCell(FormFieldBuilder.ALIGN_RIGHT, this.CaptionWidth, _lblCardStartDateCaption);
                    cardFormBuilder.AddCell(FormFieldBuilder.ALIGN_LEFT, this.InputWidth, _cboStartMonth , new LiteralControl("&nbsp;/&nbsp;"), _cboStartYear);
                    cardFormBuilder.CommitRow();
                }

                cardFormBuilder.NewRow();
                cardFormBuilder.AddCell(FormFieldBuilder.ALIGN_RIGHT, this.CaptionWidth, _lblExpirationDateCaption);
                cardFormBuilder.AddCell(FormFieldBuilder.ALIGN_LEFT, this.InputWidth, _cboExpirationMonth, new LiteralControl("&nbsp;/&nbsp;"), _cboExpirationYear);
                cardFormBuilder.CommitRow();

                if (this.ShowCardStarDate)
                {
                    cardFormBuilder.NewRow();
                    cardFormBuilder.AddCell(FormFieldBuilder.ALIGN_RIGHT, this.CaptionWidth, _lblCardIssueNumberCaption);
                    cardFormBuilder.AddCell(FormFieldBuilder.ALIGN_LEFT, this.InputWidth, _txtCardIssueNumber, new LiteralControl("&nbsp;"), _lblCardIssueNumberInfoCaption);
                    cardFormBuilder.CommitRow();

                    _txtCardIssueNumber.MaxLength = 2;
                    _txtCardIssueNumber.Columns = 2;
                }

                templateBuilder.CurrentRow = _cardFormRow;
                templateBuilder.AddCell(FormFieldBuilder.ALIGN_LEFT, Unit.Percentage(100), _tblCreditCard);
                templateBuilder.CommitRow();

                _tblPONumber.Width = Unit.Percentage(100);
                _tblPONumber.CssClass = "PurchaseOrderPaymentMethodPanel";
                FormFieldBuilder poNumberBuilder = new FormFieldBuilder(_tblPONumber);
                poNumberBuilder.NewRow();
                poNumberBuilder.AddCell(FormFieldBuilder.ALIGN_RIGHT, this.CaptionWidth, _lblPONumber);
                _txtPONumber.MaxLength = 30;
                _txtPONumber.Columns = 30;
                poNumberBuilder.AddCell(FormFieldBuilder.ALIGN_LEFT, this.InputWidth, _txtPONumber);
                poNumberBuilder.CommitRow();

                templateBuilder.CurrentRow = _poNumberRow;
                templateBuilder.AddCell(FormFieldBuilder.ALIGN_LEFT, Unit.Percentage(100), _tblPONumber);
                templateBuilder.CommitRow();

                _tblRedirect.Width = Unit.Percentage(100);
                _tblRedirect.CssClass = "RedirectPaymentMethodPanel";
                FormFieldBuilder redirectBuilder = new FormFieldBuilder(_tblRedirect);
                redirectBuilder.NewRow();
                redirectBuilder.AddCell(FormFieldBuilder.ALIGN_LEFT, this.CaptionWidth, _lblRedirectCaption);
                redirectBuilder.CommitRow();

                templateBuilder.CurrentRow = _redirectRow;
                templateBuilder.AddCell(FormFieldBuilder.ALIGN_LEFT, Unit.Percentage(100), _tblRedirect);
                templateBuilder.CommitRow();


                if (this.RequireTermsAndConditions)
                {
                    templateBuilder.NewRow();

                    Panel pnlTerms = new Panel();
                    pnlTerms.Controls.Add(_chkTermsChecked);
                    pnlTerms.Controls.Add(new LiteralControl("&nbsp;"));
                    pnlTerms.Controls.Add(new LiteralControl(this.TermsAndConditionsHTML));

                    templateBuilder.AddCell(FormFieldBuilder.ALIGN_LEFT, Unit.Percentage(100), pnlTerms);

                    templateBuilder.CommitRow();
                }

                Controls.Add(_template);

                AttachValidators();
            }
        }

        public override void RenderControl(HtmlTextWriter writer)
        {
            base.RenderControl(writer);

            if (!DesignMode && Visible)
            {
                StringBuilder script = new StringBuilder();
                script.Append("<script type=\"text/javascript\" language=\"Javascript\" >\n");
                script.Append("$add_windowLoad(\n");
                script.Append(" function() { \n");

                script.AppendFormat("   var reg = ise.Controls.PaymentTermController.registerControl('{0}');\n", this.ClientID);
                script.Append("   if(reg) {\n");
                script.AppendFormat("      reg.IsTokenization = {0}; \n", IsTokenization.ToString().ToLower());
                script.AppendFormat("      reg.IsInOnePageCheckout = {0}; \n", IsInOnePageCheckOut.ToString().ToLower());
                script.AppendFormat("      reg.CvvErrorMessage = '{0}'; \n", AppLogic.GetString("checkout1.aspx.13", Customer.Current.SkinID, Customer.Current.LocaleSetting, true));
                script.AppendFormat("      reg.setNoPaymentRequired({0});\n", this.NoPaymentRequired.ToString().ToLowerInvariant());

                 //register the options
                foreach (HtmlInputRadioButton radioOption in this._options)
                {
                    script.AppendFormat("      reg.registerOption(new ise.Controls.PaymentTermOption('{0}', '{1}', '{2}'));\n", radioOption.ClientID, radioOption.Attributes[PAYMENT_TERM_TEMP_ATTRIBUTE], radioOption.Attributes[PAYMENT_METHOD_TEMP_ATTRIBUTE]);
                    radioOption.Attributes[PAYMENT_TERM_TEMP_ATTRIBUTE] = string.Empty;
                    radioOption.Attributes[PAYMENT_METHOD_TEMP_ATTRIBUTE] = string.Empty;
                }

                script.AppendLine();

                if (null != this.ErrorSummaryControl)
                {
                    script.AppendFormat("      reg.setValidationSummary({0});", this.ErrorSummaryControl.RenderInitialization());
                    script.AppendLine();
                }

                script.AppendLine();

                script.AppendFormat("      var evaluateCardDetails = function(){{ return reg.getCurrentOption().getPaymentTerm().toUpperCase() !=  '{0}' && reg.getCurrentOption().getPaymentTerm().toUpperCase() !=  '{1}' && reg.getCurrentOption().getPaymentMethod() !=  '{2}' && reg.getCurrentOption().getPaymentMethod() == '{3}'; }}; \n", "PURCHASE ORDER", "REQUEST QUOTE", PAYMENT_METHOD_PAYPALX, PAYMENT_METHOD_CREDITCARD);

                script.AppendLine();

                // register the validators
                List<InputValidator> validators = this.ProvideValidators();
                {
                    for (int ctr = 1; ctr <= validators.Count; ctr++)
                    {
                        InputValidator current = validators[ctr - 1];
                        if (current.SupportsClientSideValidation)
                        {
                            script.AppendFormat("      var val_{0} = {1};", ctr, current.RenderInitialization());
                            script.AppendLine();
                            script.AppendFormat("      val_{0}.setEvaluationDelegate(evaluateCardDetails);", ctr);
                            script.AppendLine();
                            script.AppendFormat("      reg.registerValidator(val_{0});", ctr);
                            script.AppendLine();
                        }
                    }
                }

                script.AppendLine();

                if (this.RequireTermsAndConditions)
                {
                    script.AppendFormat("      ise.StringResource.registerString('checkoutpayment.aspx.5', '{0}');\n", this.RequireTermsAndConditionsPrompt);
                    script.AppendFormat("      reg.setRequireTermsAndConditions({0});\n", true.ToString().ToLowerInvariant());
                }

                script.Append("   }\n");

                string displayText = Security.HtmlEncode("<img src=" + AppLogic.LocateImageURL("skins/skin_" + Customer.Current.SkinID.ToString() + "/images/verificationnumber.gif") + ">");
                script.AppendFormat("    new ToolTip('{0}', 'cvv2_ToolTip', '{1}');\n", _lnkWhatIsCvv.ClientID, displayText);

                script.Append(" }\n");
                script.Append(");\n");
                script.AppendLine();

                script.Append("</script>\n");

                writer.Write(script.ToString());
            }
        }

        private void AttachValidators()
        {
            List<InputValidator> validatorsToAttach = this.ProvideValidators();

            foreach (InputValidator validator in validatorsToAttach)
            {
                this.Controls.Add(validator);
            }
        }

        protected override List<InputValidator> ProvideValidators()
        {
            List<InputValidator> defaultValidators = new List<InputValidator>();
            defaultValidators.Add(MakeRequiredInputValidator(_hdfPaymentTerm, this.PaymentTermRequiredErrorMessage));

            if (this.PaymentMethod == PAYMENT_METHOD_CREDITCARD)
            {
                RequiredInputValidator requireNameOnCard = MakeRequiredInputValidator(_txtNameOnCard, this.NameOnCardRequiredErrorMessage);
                RequiredInputValidator requireCardNumber = MakeRequiredInputValidator(_txtCardNumber, this.CardNumberRequiredErrorMessage);
                RequiredInputValidator requireCVV = MakeRequiredInputValidator(_txtCVV, this.CVVRequiredErrorMessage);
                CreditCardNumberByTypeValidator validateCardFormat =
                new CreditCardNumberByTypeValidator(_txtCardNumber,
                    _cboCardType,
                    this.UnknownCardTypeErrorMessage,
                    this.NoCardNumberProvidedErrorMessage,
                    this.CardNumberInvalidFormatErrorMessage,
                    this.CardNumberInvalidErrorMessage,
                    this.CardNumberInAppropriateNumberOfDigitsErrorMessage);

                DropDownValidator validateCardType = new DropDownValidator(_cboCardType, this.CardTypeInvalidErrorMessage);
                DropDownValidator validateExpMonth = new DropDownValidator(_cboExpirationMonth, this.ExpirationMonthInvalidErrorMessage);
                DropDownValidator validateExpYear = new DropDownValidator(_cboExpirationYear, this.ExpirationYearInvalidErrorMessage);

                requireNameOnCard.Evaluate += new CancelEventHandler(CreditCardField_Evaluate);
                requireCardNumber.Evaluate += new CancelEventHandler(CreditCardField_Evaluate);
                validateCardFormat.Evaluate += new CancelEventHandler(CreditCardField_Evaluate);
                requireCVV.Evaluate += new CancelEventHandler(CreditCardField_Evaluate);
                validateCardType.Evaluate += new CancelEventHandler(CreditCardField_Evaluate);
                validateExpMonth.Evaluate += new CancelEventHandler(CreditCardField_Evaluate);
                validateExpYear.Evaluate += new CancelEventHandler(CreditCardField_Evaluate);

                base.HandleValidationErrorEvent(validateCardFormat);
                base.HandleValidationErrorEvent(validateCardType);
                base.HandleValidationErrorEvent(validateExpMonth);
                base.HandleValidationErrorEvent(validateExpYear);

                defaultValidators.Add(requireNameOnCard);
                defaultValidators.Add(requireCardNumber);
                defaultValidators.Add(requireCVV);
                defaultValidators.Add(validateCardFormat);
                defaultValidators.Add(validateExpMonth);
                defaultValidators.Add(validateCardType);
                defaultValidators.Add(validateExpYear);
            }
            return defaultValidators;
        }

        private void CreditCardField_Evaluate(object sender, CancelEventArgs e)
        {
            e.Cancel =  this.PaymentMethod != PAYMENT_METHOD_CREDITCARD || 
                        this.PaymentTermCode.Equals("PURCHASE ORDER", StringComparison.InvariantCultureIgnoreCase) ||
                        this.PaymentTermCode.Equals("REQUEST QUOTE", StringComparison.InvariantCultureIgnoreCase) ||
                        this.PaymentMethod.Equals(PAYMENT_METHOD_PAYPALX);
        }

        #endregion

    }
}

